package com.leyou.auth.service;

import com.leyou.auth.client.UserClient;
import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LeYouException;
import com.leyou.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

/**
 * @Author: Rose
 * @Date: 2021/4/10 16:35
 * @description ${description}
 * @version: 1.0.0
 */
@Slf4j
@EnableConfigurationProperties({JwtProperties.class})
@Service
public class AuthService {

    @Autowired
    private UserClient userClient;


    @Autowired
    private JwtProperties jwtProperties;


    public String login(String username, String password) {

        // 校验用户名和密码
        User user = userClient.queryUser(username, password);
        // 生成token
        if (user == null) {
            throw new LeYouException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        try {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(user.getId());
            userInfo.setUsername(username);
            // 生成token
            String token = JwtUtils.generateTokenExpireInMinutes(userInfo, jwtProperties.getPriKey(), jwtProperties.getExpire());

            return token;
        } catch (Exception e) {
            log.info("[授权中心] 登录失败,用户名称:{}, 生成token 发生异常:{}", username, e.getMessage());
            throw new LeYouException(ExceptionEnum.CREATE_TOKEN_ERROR);
        }
    }
}
